<?php
namespace Mall\Controller;

use Common\Controller\ApiController;
use Common\Model\ModelException;
use Util\ModelUtils;
use Util\Tree;

class GoodsController extends ApiController
{
    public function recommend()
    {
        $input = $this->request();
        $page = filter($input['page'], 1);
        $perPage = filter($input['per_page'], 10);
        $perPage > 30 && $perPage = 30;
        $input = $this->request();
        $where = [];
        $where['expired_at'] = [['eq', 0], ['egt', time()], 'or'];
        
        if($input['goods_id']){  //直播间推荐商品
           $goods_id = explode(',', $input['goods_id']);
           $where['goods_id'] = ['in',$goods_id];
        }
        $count = D('Goods')->scope('valid')->where($where)->count();
        $goodslist = D('Goods')
            ->scope('valid')
            ->where($where)
            ->order('sold_num desc')
            ->page($page, $perPage)
            ->select();
        ModelUtils::belongsTo($goodslist, ['foreignKey' => 'shop_id', 'relation' => 'Shop', 'refKey' => 'shop_id']);
        ModelUtils::belongsTo($goodslist, ['foreignKey' => 'cate_id', 'relation' => 'GoodsCate', 'refKey' => 'cate_id', 'name' => 'cate']);
        $goodslist = transform('Goods', 'listview', $goodslist);
        $pagination = pagination($count, $perPage, $page);
        $this->response($goodslist, $pagination);
    }

    public function search()
    {
        $input = $this->request();
        $page = filter($input['page'], 1);
        $perPage = filter($input['per_page'], 10);
        $perPage > 30 && $perPage = 30;
        $keyword = filter($input['keyword'], '');
        $cateid = filter($input['cate_id'], '');
        $orderby = filter($input['orderby'], 'orderby');
        $direction = filter($input['direction'], 'ASC');
        $attrs = filter($input['attrs'], '');
        $ishot = filter($input['ishot']);
        $brand_id = filter($input['brand_id'], 0);
        $where = [];
        if(!empty($ishot))$where['ishot'] = (int) $ishot;
        if(!is_array($attrs)){
            $attrs = json_decode($attrs,true);
        }
        // 添加统计量
        if ($page == 1) {
            // 添加统计量
            D('Statistical')->addCount('mall_count');
            S('goods_page_lock_' . $this->token, time());
        } else {
            $lastest = S('goods_page_lock_' . $this->token);
            $where['create_time'] = ['elt', $lastest];
        }
        if ($keyword !== '') {
            $where['title'] = ['like', "%{$keyword}%"];
        }
        $condition = [];
        $query_count=0;
        // $map = [];
        $sql = 'select goods_id from bao_goods_attr where 1 and';
        if($brand_id>0){
            $where['brand_id'] = $brand_id;
        }

        foreach($attrs as $key => $attr){
            if($attr){
                // $condition['name'] = $key;
                // $condition['val'] = ['in',$attr];
                // $map['_complex'][] = $condition;
                $attr_val = implode(",", $attr);
                $query_count += 1;
                if($query_count==1){
                    $sql .="  (name = '{$key}' and val in ('{$attr_val}')) ";
                }else{
                    $sql .=" or (name = '{$key}' and val in ('{$attr_val}')) ";
                }
            }
        }
        $sql .= " group by goods_id having count(*) =".$query_count;
        $where['expired_at'] = [['eq', 0], ['egt', time()], 'or'];

        if ($cateid !== '') {
            $cate = D('GoodsCate')->find($cateid);
            if ($cate['parent_id'] == 0) {
                // 一级
                $childrenIds = D('GoodsCate')->where(['parent_id' => $cateid,'show' => 1])->getField('cate_id', true);
                
                if ($childrenIds)  $childrenIds[] = $cateid;
                $where['cate_id'] = ['in', $childrenIds];
            } else {
                $where['cate_id'] = $cateid;
            }
        }else{
            $childrenIds = D('GoodsCate')->where(['parent_id' => ['gt',0],'show' => 1])->getField('cate_id', true);
            $where['cate_id'] = ['in', $childrenIds];
        }
        $goodsIds = D('Goods')
            ->scope('valid')
            ->where($where)
            ->getField('goods_id',true);
        if($goodsIds){
               $goods_attrs = D('GoodsAttr')->scope('valid')->where(['goods_id'=>['in',$goodsIds]])->select();
               $goods_attrs = array_group($goods_attrs,'name');
               $list = [];
               foreach($goods_attrs as $attrs=>$val){
                    $list['name'] = $attrs;
                    $list['items'] = array_values(array_unique(array_column($val,'val')));
                    $attr_list[]=$list;
               }
        }    
        if($query_count>0){
            // $goods_attrs=D('GoodsAttr')->scope('valid')->where($map)->select();
            $goods_attrs = D('GoodsAttr')->query($sql);
            if($goods_attrs){
                 $goods_ids = array_column($goods_attrs,'goods_id');
                 $where['goods_id'] = ['in',$goods_ids];   
            }else{
                $where['goods_id'] = 0;
            }
        }
 
        $count = D('Goods')->scope('valid')->where($where)->count();
        $goods = D('Goods')
            ->scope('valid')
            ->where($where)
            ->page($page, $perPage)
            ->order("orderby ASC,{$orderby} {$direction}")
            ->select();
        $brands = D('Brand')->where(['delete_time'=>0])->select();
        
        
        //ModelUtils::belongsTo($goods, ['foreignKey' => 'shop_id', 'relation' => 'Shop', 'refKey' => 'shop_id']);
        ModelUtils::belongsTo($goods, ['foreignKey' => 'cate_id', 'relation' => 'GoodsCate', 'refKey' => 'cate_id', 'name' => 'cate']);
        ModelUtils::belongsTo($goods, ['foreignKey' => 'brand_id', 'relation' => 'Brand', 'name' => 'brand']);
        $goods = transform('Goods', 'listview', $goods);
        $pagination = pagination($count, $perPage, $page);
        $data['goods'] = $goods;
        $data['attrs'] = $attr_list;
        $data['brands'] = $brands;
        $this->response($data, $pagination);
    }

    public function getAll()
    {
        $input = $this->request();
        $per_page = filter($input['per_page'],6);
        $cates = D('GoodsCate')->scope('valid')->where(['show' => 1]) -> order('orderby asc')->select();
        $tree = new Tree('cate_id', 'parent_id');
        $tree->load($cates);
        $cates = transform('GoodsCate', 'listview', $tree->deepTree());
        foreach($cates as &$cate){
            $second_cate_ids = array_column($cate['children'],'cate_id');
            if($second_cate_ids){
                $goodses = D('Goods')->scope('valid')->where(['cate_id'=>['in',$second_cate_ids]])->order('goods_id desc')->limit($per_page)->select();
                $cate['goodss'] = $goodses;
                unset($cate['children']);
            }else{
                $cate['goodss'] = [];
            }
        }
        $this->response($cates);
        
        // $cates = D('GoodsCate')->scope('valid')->select();
        // ModelUtils::hasMany($cates, ['relation' => 'Goods', 'refKey' => 'cate_id', 'foreignKey' => 'cate_id', 'name' => 'goodss', 'scope' => 'valid']);
        // $cates = transform('GoodsCate', 'full', $cates);
        // $this->response($cates);
    }

      public function indexGoods()
    {
     
        $cates = D('GoodsCate')->scope('valid')->order('orderby asc')->select();
        $tree = new Tree('cate_id', 'parent_id');
        $tree->load($cates);
        $cates = transform('GoodsCate', 'listview', $tree->deepTree());
        foreach($cates as &$cate){
            $second_cate_ids = array_column($cate['children'],'cate_id');
            $goodses = D('Goods')->scope('valid')->where(['cate_id'=>['in',$second_cate_ids]])->order('goods_id desc')->limit(6)->select();
            $cate['goodss'] = $goodses;
            unset($cate['children']);
        }
        $this->response($cates);
    }

    public function getDetail($id)
    {
        $where = [];
        $where['expired_at'] = [['eq', 0], ['egt', time()], 'or'];

        $goods = D('Goods')->scope('valid')->where($where)->find($id);
        if (empty($goods)) $this->errorResponse(90001);

        $cate = D('GoodsCate')->where(['cate_id'=>$goods['cate_id'],'delete_time'=>0])->find();
        $cate_father = D('GoodsCate')->where(['cate_id'=>$cate['parent_id'],'delete_time'=>0])->find();

        if(!$cate && !$cate_father) $this->errorResponse(90001);
        D('Goods')->where(['goods_id' => $id])->setInc('views');
        ModelUtils::belongsTo($goods, ['foreignKey' => 'brand_id', 'relation' => 'Brand', 'name' => 'brand']);
        ModelUtils::belongsTo($goods, ['foreignKey' => 'shop_id', 'relation' => 'Shop', 'refKey' => 'shop_id']);
        ModelUtils::belongsTo($goods, ['foreignKey' => 'cate_id', 'relation' => 'GoodsCate', 'refKey' => 'cate_id', 'name' => 'cate']);
        $comments = D('GoodsComment')->scope('valid')->where(['goods_id'=>$goods['goods_id'],'is_checked'=>'Y'])->order('id desc')->limit(2)->select();
        ModelUtils::belongsTo($comments,['foreignKey' => 'user_id','relation' => 'Users','refKey' => 'user_id' ,'name' => 'user']);
        $goods['comments'] = $comments;
        
        $comments_count = D('GoodsComment')->scope('valid')->where(['goods_id'=>$goods['goods_id'],'is_checked'=>'Y'])->count();
        $goods['comments_count'] = $comments_count;
        //显示收藏状态
        if(M('goodsCollected')->where(['goods_id'=>$id,'user_id'=>$this->user['user_id']])->find()){
             $goods['collected'] = true;
        };
        $goods = transform('Goods', 'detail', $goods);
        $this->fillGoods($goods);
        $this->response($goods);
    }

    public function collect(){
        $input = $this->request();
        $exit = M('goodsCollected')->where(['goods_id'=>$input['goods_id'],'user_id'=>$this->user['user_id']])->find();
        if($exit){
            $this->errorResponse(90016);
        }

        $result = M('goodsCollected')->add(['user_id'=>$this->user['user_id'],'goods_id'=>$input['goods_id'],'create_time'=>time()]);
        if($result){
            $data['result'] = 'success';
        }else{
            $data['result'] = 'failure';
        }
            $this->response($data);

    }

     public function uncollect(){
        $input = $this->request();
        $exit = M('goodsCollected')->where(['goods_id'=>$input['goods_id'],'user_id'=>$this->user['user_id']])->find();
        if(!$exit){
            $this->errorResponse(90017);
        }

        $result = M('goodsCollected')->where(['user_id'=>$this->user['user_id'],'goods_id'=>$input['goods_id']])->delete();
        if($result){
            $data['result'] = 'success';
        }else{
            $data['result'] = 'failure';
        }
            $this->response($data);
    }

    private function fillGoods(&$goods)
    {
        $user = get_user();
        $attrs = D('GoodsAttr')->where(['goods_id' => $goods['goods_id'], 'status' => '1'])->select();
        $attrs = list_keep($attrs, ['id', 'name', 'val']);


        $specs = D('GoodsSpec')->where(['goods_id' => $goods['goods_id'], 'status' => '1'])->select();
        $specs = array_group_by($specs, 'name');
        foreach ($specs as &$spec) {
            $spec['items'] = list_keep($spec['items'], ['id', 'val']);
        }

        $skus = D('GoodsSku')->field('name,price,wholesale_price,stock,photo')->where(['goods_id' => $goods['goods_id']])->select();
        // 售价判断
        foreach ($skus as &$sku) {
            $sku['price'] = $user['role'] === '2' ? $sku['wholesale_price'] : $sku['price'];
            $sku['photo'] = !empty($sku['photo'])?explode(",",$sku['photo']):[];
            unset($sku['wholesale_price']);
        }
        $goods['attrs'] = $attrs;
        $goods['specs'] = $specs;
        $goods['skus'] = $skus;
    }
    
}
